package com.ruoyi.common.utils;

import com.ruoyi.common.utils.redis.JedisPoolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OrderUtil {

    @Autowired
    private JedisPoolUtils jedisPoolUtils;

    //24小时后自动失效
    private static final long REQUEST_EXIT_MILLISECONDS = 24*60*60*1000L;
    //测试用
    //private static final long REQUEST_EXIT_MILLISECONDS = 10*1000L;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    /**
     * 创建不连续的订单号
     *
     * @param pix
     * 数据中心编号
     * @return 唯一的、不连续订单号
     */
    public synchronized String getOrderNoByUUID(String pix) {
        Integer uuidHashCode = UUID.randomUUID().toString().hashCode();
        if (uuidHashCode < 0) {
            uuidHashCode = uuidHashCode * (-1);
        }
        String date = simpleDateFormat.format(new Date());
        return pix  + date + uuidHashCode;
    }

    /**
     * 获取同一秒钟 生成的订单号连续
     *
     * @param pix
     * @param key
     * 数据中心编号
     * @return 同一秒内订单连续的编号
     */
    public synchronized String getOrderNoByAtomic(String pix,String key) {
        String date = simpleDateFormat.format(new Date());
        Jedis jedis = jedisPoolUtils.getJedis();
        Long no = 0L;
        try{
            no = jedis.incr(key);
        }finally {
            jedis.pexpire(key, REQUEST_EXIT_MILLISECONDS);
            jedis.close();
        }

        return pix + date + String.format("%05d", no);
    }
}
